package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    /*
     * 微信小程序登录
     * */
    @Override
    public Map<String, Object> wxLogin(String code) {
        //调用 api方法获取openid。
        String openid = null;
        try {
            openid = wxMaService.jsCode2SessionInfo(code).getOpenid();
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        //通过openid查询用户信息表
        UserInfo userInfo = userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));
        if (userInfo == null) {
            //  如果数据库中没有这个对象
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname("听友" + System.currentTimeMillis());
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            userInfoMapper.insert(userInfo);
            //始化账户信息：第一种方式：openFeign远程调用！第二种方式：mq
            rabbitService.sendMessage(MqConst.EXCHANGE_USER, MqConst.ROUTING_USER_REGISTER, userInfo.getId());
        }

        //声明一个token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //用户信息存储到缓存中。
        String userLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
        this.redisTemplate.opsForValue().set(userLoginKey, userInfo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return map;
    }

    /*
     * 微信小程序获取用户信息
     * */
    @Override
    public UserInfoVo getUserInfo(Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        return userInfoVo;
    }

    /**
    * 根据专辑id查询用户是否购买声音列表
    * @param albumId 专辑ID
    * @param userId 用户ID
    * @param needPaidTrackIdList 需要支付的声音ID列表
    * @return 包含每个声音ID及其是否需要支付的映射，1表示需要支付，0表示已支付
    */
    @Override
    public Map<Long, Integer> userIsPaidTrack(Long albumId, Long userId, List<Long> needPaidTrackIdList) {
        // 查询用户是否购买了指定的专辑
        UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getAlbumId, albumId).eq(UserPaidAlbum::getUserId, userId));

        // 如果用户没有购买该专辑，则所有声音都需要支付
        if (null == userPaidAlbum){
            Map<Long, Integer> map = needPaidTrackIdList.stream().collect(Collectors.toMap(trackId -> trackId, v-> 1));
            return map;
        }

        // 查询用户已经支付的声音列表
        List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>().in(UserPaidTrack::getTrackId, needPaidTrackIdList));
        // 如果已支付的声音列表为空，则所有声音都需要支付
        if (CollectionUtils.isEmpty(userPaidTrackList)){
            return needPaidTrackIdList.stream().collect(Collectors.toMap(trackId -> trackId, v-> 0));
        } else {
            // 创建一个映射来记录每个声音是否需要支付
            Map<Long, Integer> map = new HashMap<>();
            for (Long trackId : needPaidTrackIdList) {
                // 如果声音不在已支付列表中，则标记为需要支付
                if (!userPaidTrackList.contains(trackId)){
                    map.put(trackId, 1);
                } else {
                    // 否则，标记为已支付
                    map.put(trackId, 0);
                }
            }
            return map;
        }
    }
}

